package com.lishem.carl._07tree;

import com.lishem.common.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * https://leetcode.cn/problems/find-bottom-left-tree-value/description/
 * <p>
 * 给定一个二叉树的 根节点 root，请找出该二叉树的 最底层 最左边 节点的值。
 * <p>
 * 假设二叉树中至少有一个节点。
 */
public class _20LetCode513_找树左下角的值 {

    private int depth = 0;
    private int res = 0;

    /**
     * 递归
     */
    public int findBottomLeftValue(TreeNode root) {
        res = root.val;
        findLeftValue(root, 0);
        return res;
    }

    private void findLeftValue(TreeNode root, int depth) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            if (depth > this.depth) {
                this.depth = depth;
                res = root.val;
            }
        }
        if (root.left != null) {
            findLeftValue(root.left, depth + 1);
        }
        if (root.right != null) {
            findLeftValue(root.right, depth + 1);
        }
    }


    /**
     * 迭代
     */
    public int findBottomLeftValue1(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int res = root.val;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                root = queue.poll();
                if (i == 0) {
                    res = root.val;
                }
                if (root.left != null) {
                    queue.add(root.left);
                }
                if (root.right != null) {
                    queue.add(root.right);
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        _20LetCode513_找树左下角的值 sol = new _20LetCode513_找树左下角的值();
        TreeNode root = new TreeNode(2);
        root.left = new TreeNode(1);
        root.right = new TreeNode(3);
        System.out.println(sol.findBottomLeftValue(root));
        System.out.println(sol.findBottomLeftValue1(root));

    }

}
